package com.lxw.oa.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class POIWordUtil {

    public static XWPFDocument replaceWordModel(Map<String, String> map,String srcPath) {
        XWPFDocument document=null;
        try {
            document = new XWPFDocument(POIXMLDocument.openPackage(srcPath));
            /**
             * 替换段落中的指定文字
             */
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                Set<String> set = map.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    List<XWPFRun> run=paragraph.getRuns();
                    for(int i=0;i<run.size();i++)
                    {
                        if(run.get(i).getText(run.get(i).getTextPosition())!=null &&
                                run.get(i).getText(run.get(i).getTextPosition()).equals(key))
                        {
                            /**
                             * 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                             * 就可以把原来的文字全部替换掉了
                             */
                            run.get(i).setText(map.get(key),0);
                        }
                    }
                }
            }
            /**
             * 替换表格中的指定文字
             */
            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
                XWPFTable table = (XWPFTable) itTable.next();
                int count = table.getNumberOfRows();
                for (int i = 0; i < count; i++) {
                    XWPFTableRow row = table.getRow(i);
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        for (Map.Entry<String, String> e : map.entrySet()) {
                            if (cell.getText().equals(e.getKey())) {
                                cell.removeParagraph(0);
                                cell.setText(e.getValue());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return document;
    }

	public static XWPFDocument replaceWordModelXWPF(Map<String, String> textMap,String inputUrl, List<String[]> tableList) {
        XWPFDocument document=null;
        try {
            document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
            POIWordUtil.changeText(document, textMap);
            POIWordUtil.changeTable(document, textMap, tableList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    }
	
    public static void changeText(XWPFDocument document, Map<String, String> textMap){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String dqsj = sdf.format(date);
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            String text = paragraph.getText();
            if(checkText(text)){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                	String v = run.toString();
                	if(v.contains("dqsj")) {
                		run.setText(dqsj,0);
                	}
                }
            }
        }
    }
    
    public static void changeTable(XWPFDocument document, Map<String, String> textMap, List<String[]> tableList){
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            XWPFTable table = tables.get(i);
            if(table.getRows().size()>1){
                if(checkText(table.getText())){
                    List<XWPFTableRow> rows = table.getRows();
                    eachTable(rows, textMap);
                } else {
                    
                }
            }
        }
    }
    
    public static void eachTable(List<XWPFTableRow> rows, Map<String, String> textMap){
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                if(checkText(cell.getText())){
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        String text = "";
                        for (XWPFRun run : runs) {
                        	text += run.toString();
                        }
                        if("${zp}".equalsIgnoreCase(text)) {
                        	int len = paragraph.getRuns().size();
                            for(int i=0; i<len; i++) {
                            	XWPFRun run = runs.get(i);
                            	run.setText("",0);
                            }
                            changeImage(runs.get(len-1), textMap.get("${zp}"));
                        } else {
                        	int len = paragraph.getRuns().size();
                            for(int i=0; i<len-1; i++) {
                            	XWPFRun run = runs.get(i);
                            	run.setText("",0);
                            }
                            XWPFRun run = runs.get(len-1);
                            run.setText(changeValue(text, textMap),0);
                        }
                    }
                }
            }
        }
    }
    
    public static boolean checkText(String text){
        boolean check  =  false;
        if(text.indexOf("$")!= -1){
            check = true;
        }
        return check;
    }
    
    public static String changeValue(String value, Map<String, String> textMap){
        Set<Entry<String, String>> textSets = textMap.entrySet();
        for (Entry<String, String> textSet : textSets) {
            String key = (textSet.getKey()).toLowerCase();
            if(value.indexOf(key)!= -1){
                value = textSet.getValue();
            }
        }
        if(checkText(value)){
            value = "";
        }
        return value;
    }
    
    public static void changeImage(XWPFRun run, String image) {
    	try {
			FileInputStream is = new FileInputStream(new File(image));
			run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(93), Units.toEMU(109));
			if(is != null){
				is.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

}
